import axios from "axios";
// import { Message } from "element-ui";
import { Loading } from "element-ui";
import qs from "qs";
import router from "@/router";

const noLoadingUrl = [];

const default_options = {
  lock: true,
  text: "加载中...",
};

let loading;
function startLoading() {
  // 使用Element loading-start 方法
  loading = Loading.service(default_options);
}
function endLoading() {
  // 使用Element loading-close 方法
  loading.close();
}

let needLoadingRequestCount = 0;
export function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount += 1;
}
// 调用 tryHideFullScreenLoading()方法，needLoadingRequestCount-1。needLoadingRequestCount为 0时，结束 loading
export function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount -= 1;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
}

axios.defaults.timeout = 30000;
axios.defaults.baseURL =
  process.env.NODE_ENV === "production" ? "http://127.0.0.1:8081" : "/api";
// http request 拦截器
axios.interceptors.request.use(
  (config) => {
    if (!config.headers) {
      config.headers = {
        "Content-Type": "application/json",
      };
    }
    if (!noLoadingUrl.find((item) => config.url.indexOf(item) > -1)) {
      // request拦截器中调用 showFullScreenLoading()
      showFullScreenLoading();
    }
    const token = localStorage.getItem("robot_login_token");
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

//http response 拦截器
axios.interceptors.response.use(
  (response) => {
    // response拦截器中调用 tryHideFullScreenLoading()
    tryHideFullScreenLoading();
    if (response.data.code === 401) {
      // 没权限
      localStorage.removeItem("robot_login_token");
      router.replace({ path: "/login" });
    }
    return response;
  },
  (error) => {
    // response拦截器中调用 tryHideFullScreenLoading()
    tryHideFullScreenLoading();
    return Promise.reject(error);
  }
);

/**
 * 封装get方法
 * @param url
 * @param data
 * @param loading 是否loading
 * @returns {Promise}
 */

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params,
      })
      .then((response) => {
        resolve(response.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @param loading 是否loading
 * @returns {Promise}
 */
export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data, loading).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

/**
 * 封装post请求 x-www-form-urlencoded格式传参
 * @param url
 * @param data
 * @param loading 是否loading
 * @returns {Promise}
 */
export function postWithFormData(url, data = {}) {
  return new Promise((resolve, reject) => {
    let param = data;
    if (data.needStringify) {
      delete data.needStringify;
      param = qs.stringify(data);
    }
    axios({
      method: "post",
      url,
      data: param,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    }).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @param loading 是否loading
 * @returns {Promise}
 */
export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data, loading).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

/**
 * 封装delete请求
 * @param url
 * @param data
 * @param loading 是否loading
 * @returns {Promise}
 */
export function deleteApi(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios
      .delete(url, {
        params: data,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      })
      .then(
        (response) => {
          resolve(response.data);
        },
        (err) => {
          reject(err);
        }
      );
  });
}
